package com.web.fsc.controller;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.web.fsc.domain.Paper;
import com.web.fsc.service.IPaperService;

@Controller
public class PaperController {

	@Autowired
	private IPaperService paperService;
	Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequestMapping(value = "listPaper/{category}")
	public ModelAndView listPaper(ModelAndView mav, @PathVariable String category, String system) {
		List<Paper> paperList = new ArrayList<>();
		logger.info("system:" + system + ",category:" + category);
		if (system.equals("all"))
			paperList = paperService.listByCategory(category);
		else
			paperList = paperService.listBySystem(category, system);
		mav.addObject("paperList", paperList);
		mav.addObject("category", category);
		mav.setViewName("listPaper");
		return mav;
	}

	@RequestMapping(value = "listAllPaper")
	@ResponseBody
	public ModelAndView listAllPaper(ModelAndView mav) {
		List<Paper> paperAllList = new ArrayList<>();
		paperAllList = paperService.listAll();
		mav.addObject("paperAllList", paperAllList);
		mav.setViewName("admin");
		return mav;
	}

	@RequestMapping(value = "searchPaper")
	public ModelAndView searchPaper(ModelAndView mav, String key) {
		List<Paper> searchResult = new ArrayList<>();
		searchResult = paperService.search(key);
		if (searchResult.size() > 1) {
			for (Paper paper : searchResult)
				logger.info(String.valueOf(paper));
		}
		mav.addObject("searchResult", searchResult);
		mav.setViewName("index");
		return mav;
	}

	@RequestMapping(value = "upload")
	public String upload(MultipartFile file, Paper paper) {
		logger.info(paper.getAuthor());
		paperService.add(file, paper);
		return "upload";
	}

	@RequestMapping(value = "deletePaper")
	public ModelAndView delete(Long id, ModelAndView mav) {
		if (id != null)
			paperService.delete(id);
		List<Paper> paperAllList = new ArrayList<>();
		paperAllList = paperService.listAll();
		mav.addObject("paperAllList", paperAllList);
		mav.setViewName("admin");
		return mav;
	}

	@RequestMapping(value = "download")
	public String download(Long fileid) {
		logger.info(String.valueOf(fileid));
		paperService.download(fileid);
		return null;
	}
}
